import React, { useEffect } from 'react';

import { ReactComponent as CloseCircle } from '@/assets/images/auth/CloseCircle.svg';
import { Container } from '@/entities/auth';
import {
  clearEmailStatus,
  registrationByEmail,
  setCheckAuth,
  setEmailAuthProcess,
} from '@/entities/auth/model/actions';
import { getAuthProcessEmail, getIsAuth } from '@/entities/auth/model/selectors';
import { BackButton } from '@/features/BackButton';
import { Overlay } from '@/pagesComponents/Auth/ui/Overlay';
import { innerUrls } from '@/shared/constants/urls';
import { useKeyboard } from '@/shared/lib/hooks/useKeyboard';
import { useAppDispatch, useAppSelector } from '@/shared/store';
import { Button, ButtonVariants, FlexWrapper, Input, Snackbar, Title } from '@/shared/ui';
import cn from 'classnames';
import { jwtDecode } from 'jwt-decode';
import { useRouter } from 'next/router';
import { useSnackbar } from 'notistack';
import { useWindowSize } from 'usehooks-ts';

import s from './RegistrationPage.module.scss';

export const RegistrationPage = () => {
  const email = useAppSelector(getAuthProcessEmail);

  const [password, setPassword] = React.useState<string>(''); // пароль для авторизации или регистрации
  const [isPasswordHidden, setPasswordHidden] = React.useState<boolean>(true); // состояние скрытого пароля
  const [emailRepeat, setEmailRepeat] = React.useState<string>(''); // повторение емаила
  const [isCorrectEmailShown, setIsCorrectEmailShown] = React.useState<boolean>(false);
  const { enqueueSnackbar } = useSnackbar();
  const isAuth = useAppSelector(getIsAuth);
  const { height } = useWindowSize();

  const handleEmailRepeat = (event: React.ChangeEvent<HTMLInputElement>) => {
    setIsCorrectEmailShown(false);
    const { value } = event.target;
    setEmailRepeat(value);
  };

  useEffect(() => {
    if (!email || !emailRepeat) {
      return;
    }
    setIsCorrectEmailShown(false);
  }, [email, emailRepeat]);

  const dispatch = useAppDispatch();
  const router = useRouter();
  const { width } = useWindowSize();

  const handleSetEmail = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target;
    dispatch(setEmailAuthProcess(value.replace(/\s/g, '')));
  };

  const handleClearEmail = () => {
    dispatch(setEmailAuthProcess(''));
  };

  const handleSetPassword = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.target;
    setPassword(value);
  };

  const handleRegisterWithEmail = (email: string, password: string) => {
    dispatch(registrationByEmail({ email, password }))
      .unwrap()
      .then((res) => {
        if (!res.accessToken) {
          return;
        }
        const decodedToken: {
          email?: string;
          exp: number;
          iat: string;
          shi: any[];
          sub: number;
        } = jwtDecode(res.accessToken);
        dispatch(setCheckAuth({ userId: decodedToken.sub, email: decodedToken?.email, expiresIn: decodedToken.exp }));
        enqueueSnackbar('Успешно авторизован', {
          variant: 'success',
          content: (key, message) => <Snackbar id={key} message={message} size="md" variant="success" />,
        });
        router.push(innerUrls.main).then(() => {
          router.reload();
        });
      })
      .catch((e) => {
        enqueueSnackbar(`Ошибка при регистрации: ${e}`, {
          variant: 'error',
          content: (key, message) => <Snackbar id={key} message={message} size="md" variant="error" />,
        });
        router.push(innerUrls.auth.email);
      });
  };

  const handleGoBack = () => {
    router.push(innerUrls.auth.email);
    dispatch(clearEmailStatus());
  };

  React.useEffect(
    () => () => {
      dispatch(clearEmailStatus());
    },
    [],
  );

  React.useEffect(() => {
    if (!email) {
      const destination = isAuth ? innerUrls.main : innerUrls.auth.email;
      router.push(destination);
    }
  }, []);
  useKeyboard('Escape', handleGoBack);
  useKeyboard('Enter', () => {
    if (!(emailRepeat !== email || password.length <= 6)) {
      handleRegisterWithEmail(emailRepeat, password);
    }
  });

  React.useEffect(() => {
    if (width > 768) {
      document.body.style.overflow = 'hidden';
    }
    return () => {
      document.body.style.overflow = 'auto';
    };
  }, []);

  const handleEmailRepeatClear = () => {
    setIsCorrectEmailShown(false);
    setEmailRepeat('');
  };
  return (
    <Overlay isStart={height < 800}>
      <Container>
        <FlexWrapper isStart>
          {width > 1024 && (
            <div className={s.closeCircle} onClick={() => handleGoBack()}>
              <CloseCircle />
            </div>
          )}
          {width < 1024 && <BackButton className={s.back} />}
          <Title size="l" tag="h2">
            Регистрация
          </Title>
        </FlexWrapper>
        <FlexWrapper className={s.wrap}>
          <h6 className={s.password}>Почта</h6>
          <Input
            data-testid="input-email_first"
            htmlFor="emailRegId"
            // hidden={isPasswordHidden}
            isClose={email.length > 0}
            isEmailField
            onChange={handleSetEmail}
            onClear={() => handleClearEmail()}
            value={email}
          />
        </FlexWrapper>
        <FlexWrapper className={s.wrap}>
          <h6 className={cn(s.password)}>Повторите почту</h6>
          <Input
            accepted={emailRepeat === email && emailRepeat !== '' && email !== ''}
            data-testid="input-email_repeat"
            htmlFor="emailRepRegId"
            isAutoFocus={width > 768}
            isClose={emailRepeat.length > 0}
            isEmailField
            isNotAccepted={isCorrectEmailShown && emailRepeat.length !== 0}
            isNotAcceptedText="Почта не совпадает"
            onBlur={() => {
              if (emailRepeat !== email && email !== '' && emailRepeat !== '') {
                setTimeout(() => {
                  setIsCorrectEmailShown(true);
                }, 100);
              }
            }}
            onChange={handleEmailRepeat}
            onClear={handleEmailRepeatClear}
            value={emailRepeat}
          />
        </FlexWrapper>
        <FlexWrapper className={s.wrap}>
          <h6 className={s.password}>Придумайте пароль</h6>
          <Input
            autoFocus={false}
            data-testid="input-password"
            handleHidePassword={() => setPasswordHidden(false)}
            handleShowPassword={() => setPasswordHidden(true)}
            hidden={isPasswordHidden}
            htmlFor="passwordReg"
            isNotAcceptedText="Минимум 6 символов"
            isPasswordField
            isPasswordFieldReg
            isUnfocusedValidated
            onChange={handleSetPassword}
            type={isPasswordHidden ? 'password' : 'text'}
            value={password}
          />
        </FlexWrapper>
        <div className={cn(s.insideBlock)}>
          <Button
            data-testid="button-register"
            disabled={emailRepeat !== email || password.length < 6}
            onClick={() => handleRegisterWithEmail(emailRepeat, password)}
            variant={ButtonVariants.Primary}
          >
            Создать профиль
          </Button>
          <p className={s.exist} style={{ alignSelf: 'center', color: '#ABABAB' }}>
            Есть профиль?{' '}
            <Button
              className={s.forgot}
              data-testid="button-login"
              onClick={() => handleGoBack()}
              variant={ButtonVariants.Link}
            >
              Войти
            </Button>
          </p>
        </div>
      </Container>
    </Overlay>
  );
};
